/*
 * Copyright 2016 Freelander
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.handong.handserialprogram.module.base;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.ViewUtil;

import static com.handong.handserialprogram.utils.SystemUtil.updateVoiceLevel;


/**
 * Created by Jun on 2016/4/29.
 */
public abstract class BaseActivity<P extends BasePresenter> extends FragmentActivity implements View.OnClickListener {

    private static final String TAG = BaseActivity.class.getSimpleName();

    protected Fragment mCurrFragment;
    private int mFragmentId;

    protected boolean mIsResume = false;

    protected P mPresenter;

    private FrameLayout mHomeLayout, mOptionLayout;
    private TextView mCenterTitle, mOptionText;
    private ImageView optionImage;

    private MaterialDialog mLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //屏蔽锁屏
//        AppUtil.setKeyguardEnable(this,false);
        setContentView(getContentViewID());
        mPresenter = createPresenter();
        initViewByID();
        initViewDataRes();
        JLog.d(TAG, this.getClass().getSimpleName() + " onCreate");
    }


    @Override
    protected void onResume() {
        super.onResume();
        mIsResume = true;
        JLog.d(TAG, this.getClass().getSimpleName() + " onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        mIsResume = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        JLog.d(TAG, this.getClass().getSimpleName() + " onStop");
    }

    public boolean isResume() {
        return mIsResume;
    }

    protected abstract P createPresenter();

    protected abstract void initViewByID();

    protected abstract void initViewDataRes();

    protected int getContentViewID() {
        return 0;
    }

    protected void initHeaderLayout(boolean isHome) {
        mHomeLayout = (FrameLayout) findViewById(R.id.headerBackLayout);
        mOptionLayout = (FrameLayout) findViewById(R.id.headerOptionLayout);
        mCenterTitle = (TextView) findViewById(R.id.headerCenterTitle);
        mOptionText = (TextView) findViewById(R.id.headerOptionItem);
        optionImage=findView(R.id.headerOptionIcon);
        if (!isHome) {
            ImageView homeIcon = (ImageView) findViewById(R.id.headerBackLayoutIcon);
            homeIcon.setImageResource(R.drawable.ic_menu_back_144);
        }
        mHomeLayout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
    }

    /**
     * 数据加载框
     */
    public void showLoadDialog(String content) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new MaterialDialog.Builder(this)
                    .progress(true, 0)
                    .content(content)
                    .canceledOnTouchOutside(false)
                    .build();
        } else {
            mLoadingDialog.setContent(content);
        }
        ViewUtil.removeAllKeyListener(mLoadingDialog);
    }

    public boolean isLoadingShowing() {
        return mLoadingDialog == null ? false : mLoadingDialog.isShowing();
    }

    public void dismissLoadingDialog() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    public void setFrameId(int mFragmentId) {
        this.mFragmentId = mFragmentId;
    }

    protected void toFragment(Fragment toFragment) {
        if (mCurrFragment == null) {
            showShortToast("mCurrFragment is null!");
            return;
        }
        if (toFragment == null) {
            showShortToast("toFragment is null!");
            return;
        }
        if (toFragment.isAdded()) {
            getSupportFragmentManager().beginTransaction().hide(mCurrFragment)
                    .show(toFragment).commit();
        } else {
            getSupportFragmentManager().beginTransaction().hide(mCurrFragment)
                    .add(mFragmentId, toFragment).show(toFragment)
                    .commit();
        }
        mCurrFragment = toFragment;
    }

    public Fragment getCurrFragment() {
        return mCurrFragment;
    }

    public void setCurrFragment(Fragment mCurrFragment) {
        this.mCurrFragment = mCurrFragment;
    }

    public void showShortToast(String msg) {
        AppUtil.showShortToast(this, msg);
    }

    public void showLongToast(String msg) {
        AppUtil.showLengthToast(this, msg);
    }
    protected void openActivity(Class<? extends BaseActivity> toActivity) {
        openActivity(toActivity, null);
    }

    public void openActivity(Class<? extends BaseActivity> toActivity, Bundle parameter) {
        Intent intent = new Intent(this, toActivity);
        if (parameter != null) {
            intent.putExtras(parameter);
        }
        startActivity(intent);
        overridePendingTransition(R.anim.push_left_in, R.anim.anim_no);
    }

    public void openActivityForReuslt(Class<? extends BaseActivity> toActivity, Bundle parameter,int requestCode) {
        Intent intent = new Intent(this, toActivity);
        if (parameter != null) {
            intent.putExtras(parameter);
        }
        startActivityForResult(intent,requestCode);
        overridePendingTransition(R.anim.push_left_in, R.anim.anim_no);
    }

    public void openActivityFinishLast(Class<? extends BaseActivity> toActivity, Bundle parameter) {
        Intent intent = new Intent(this, toActivity);
        if (parameter != null) {
            intent.putExtras(parameter);
        }
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.anim_no);
    }

    public void openActWithAnim(Class<? extends FragmentActivity> cls, Bundle attr, int index, int requestCode) {
        Intent intent = new Intent(this, cls);
        if (attr != null) {
            intent.putExtras(attr);
        }
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.push_left_in, R.anim.anim_no);
    }

    //        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (isExit) {
//                if ((System.currentTimeMillis() - mExitTime) > 2000) {
//                    showShortToast("再按一次退出程序");
//                    mExitTime = System.currentTimeMillis();
//                } else {
//                    finish();
//                }
//                return true;
//            }
//        }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            updateVoiceLevel(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        return super.onKeyLongPress(keyCode, event);
    }

    protected void openNetwork() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .content(R.string.dialog_content_open_network)
                .negativeText(R.string.dialog_positive_setting)
                .negativeColorRes(R.color.back_ground_green)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        // 跳转到系统的网络设置界面
                        Intent intent = null;
                        // 先判断当前系统版本
                        if (android.os.Build.VERSION.SDK_INT > 10) {  // 3.0以上
                            intent = new Intent(Settings.ACTION_SETTINGS);
                        } else {
                            intent = new Intent();
                            intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
                        }
                        startActivity(intent);
                    }
                })
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     * 为ActionBar绑定监听事件。
     *
     * @param title
     */
//    protected void setToolbar(String title) {
//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
//
//        ActionBar bar = getSupportActionBar();
//        bar.setTitle(title);
//        bar.setDisplayHomeAsUpEnabled(true);
//        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
//    }

    public void setCenterTitle(String title) {
        mCenterTitle.setText(title);
    }

    public void setCenterTitle(int resID) {
        mCenterTitle.setText(resID);
    }

    public void setOptionText(String text) {
        mOptionLayout.setVisibility(View.VISIBLE);
        mOptionLayout.setOnClickListener(this);
        mOptionText.setText(text);
        mOptionText.setVisibility(View.VISIBLE);
        optionImage.setVisibility(View.GONE);
    }

    public void setOptionText(int resId) {
        mOptionLayout.setVisibility(View.VISIBLE);
        mOptionLayout.setOnClickListener(this);
        mOptionText.setText(resId);
        mOptionText.setVisibility(View.VISIBLE);
        optionImage.setVisibility(View.GONE);
    }

    /*public void setOptionOnClick() {
        mOptionLayout.setVisibility(View.VISIBLE);
        mOptionLayout.setOnClickListener(this);
        mOptionItem.setVisibility(View.VISIBLE);
        //mOptionItem.setVisibility(View.GONE);
    }*/

    public void setOptionIcon(int resID) {
        mOptionLayout.setOnClickListener(this);
        mOptionLayout.setVisibility(View.VISIBLE);
        mOptionText.setVisibility(View.GONE);
        optionImage.setVisibility(View.VISIBLE);
        optionImage.setImageResource(resID);

    }

    @Override
    public void finish() {
        super.finish();
        finshAnimtion();
    }

    public void finshAnimtion(){
        overridePendingTransition(R.anim.anim_no, R.anim.push_right_out);
    }

    protected <T extends View> T findView(int resId) {
        return (T) (findViewById(resId));
    }
    @Override
    protected void onDestroy() {
        JLog.d(TAG, this.getClass().getSimpleName() + " onDestroy");
        mLoadingDialog = null;
        if (mPresenter != null) {
            mPresenter.exit();
            mPresenter = null;
        }
        super.onDestroy();
    }
}
